package com.ews.onlineexchange.service.schedule;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.RejectRecord;
import com.ews.onlineexchange.model.ServiceSupplier;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class SupplierValidateTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	
//	@PostConstruct
	public void init() {
		ScheduleExpression schedule = new ScheduleExpression();	
		schedule.hour(1);
		timerService.createCalendarTimer(schedule, new TimerConfig("supplierValidatorTimer", false));
		
//		check();
	}
	
	private static final String QUERY_ALL_VALID_SUPPLIER_EQL = ""
			+ "	SELECT			ss"
			+ "	FROM			ServiceSupplier ss "
			+ "	WHERE			ss.valid = true "
			+ "	AND				ss.busnissAllotedTime IS NOT NULL";
//	@Timeout
	@Schedule(hour="1", minute="0", second="0", info = "supplierValidatorTimer", persistent = false)
	public void check() {
		System.out.println("===================================================================");
		System.out.println("Supplier Validate Timer Runned");
		System.out.println("===================================================================");
		Date now = new Date();
		
//		Calendar nowCal = Calendar.getInstance();
//		if (nowCal.get(Calendar.HOUR_OF_DAY) - 1 != 0)
//			return;
//		
		Session session = (Session) entityManager.getDelegate();
		session.setCacheMode(CacheMode.IGNORE);
		session.setFlushMode(FlushMode.MANUAL);
		Query query = session.createQuery(QUERY_ALL_VALID_SUPPLIER_EQL);
		ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
		long count = 0L;
		
		while (sr.next()) {
			ServiceSupplier serviceSupplier = (ServiceSupplier) sr.get(0);
			if (serviceSupplier.getBusnissAllotedTime().before(now)) {
				RejectRecord rejectRecord = new RejectRecord();
				rejectRecord.setReason("营业期限到期!");
				serviceSupplier.setCurrRejectRecord(rejectRecord);
				serviceSupplier.getHistoryRejectRecords().add(rejectRecord);
				serviceSupplier.setValid(false);
				serviceSupplier.setAuditted(false);
				session.update(serviceSupplier);
			}
			
			count++;
			if (count % 200 == 0) {
				session.flush();
			}
		}
		session.flush();
	}
	
	@PreDestroy	
	public void preDestroy() {		
//		System.out.println("============================================================");
//		System.out.println("All timer cancelled");
//		System.out.println("============================================================");
//		
//		Collection<Timer> timers = timerService.getAllTimers();
//		for (Timer timer : timers) {
//			System.out.println(timer.getInfo());
//			timer.cancel();
//		}
	}
}
